from django.http import JsonResponse
from rest_framework.routers import DefaultRouter

class NoRootAPIRouter(DefaultRouter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.root_view_name = None  # 禁止设置根视图名称，以避免其被包含在URL配置中

    """
        A router that does not include the root API view.
        """

    def get_api_root_view(self, api_urls=None):
        """
        Return a default view for the API root.
        """

        def default_view(request):
            """
            A simple default view for the API root.
            """
            data = {
                'message': 'Welcome to the API!',
            }
            return JsonResponse(data)

        return default_view
    def get_urls(self):
        original_root_view_name = self.root_view_name
        try:
            # Temporarily clear the root_view_name to avoid generating the root view
            self.root_view_name = None
            urls = super().get_urls()
        finally:
            # Restore the original value of root_view_name
            self.root_view_name = original_root_view_name

        # 返回处理后的urls
        return urls